#include "luc\watershed.h"
#include "ip\filter.h"
//#include "ip\MoreFiltering.cpp"
#include "ip\graymorphology.h"
#include "my\ImageConvert.h"
#include "Image.H"
#include "IO.H"
#include "Util.H"

using namespace pip;
using namespace std;

int main(int argc, char **argv)
{
		Stopwatch sw;
		sw.start();
		if (argc < 2){
			cout << "\nUsage: PROGRAMNAME -i INPUT-FILENAME \n { -o OUTPUT-FILENAME }\n";
			cout << "If no image is passed - the lungs.pip Image is assumed. (from region growing assignment - 30MB) \n";
		}

        // Store commandline args in stl container
        vector<string> args(argv, argv+argc);

        // Variables to be read from the commandline
        string program, inputfile(""), outputfile = "result.pip";
        
        // Read the arguments.
        getProgramName(args, program);
        getScalarArg(args, "-i", inputfile);
        getScalarArg(args, "-o", outputfile);

		Image<unsigned char> in;
		Image<unsigned char> output;


		
			if (!importFile(in, inputfile)) {
				cout <<  "can't read file";
			}


		double s_final  = 12;
		double stepsize = 0.4;
		int count(0),xd(in.dim(0));


		Image<float> result(Dimension(xd*4,in.dim(1),int(s_final/stepsize)));
		Image<unsigned char> blur,tmp,tmp2,se;
		Image<float> inputf,outputf,ero,dil,grad(Dimension(xd,in.dim(1)));
		convertUnsignedCharToFloat(in, inputf);
		discStructureElement(se,3);

		for(double s=0; s <= s_final; s+=stepsize){	
			gauss(inputf, outputf, float(s), 0, 0, 5);
			convertFloatToUnsignedChar(outputf,blur);
			grayDilate(outputf, dil,se);
			grayErode(outputf, ero,se);
			for(int x=0;x<xd;++x){
				for(int y=0;y<in.dim(1);++y){
					grad(x,y)=dil(x,y)-ero(x,y);
				}
			}
			convertFloatToUnsignedChar(grad,tmp);
			//cannyEdgeDetector(tmp, outputf,1);
			//convertFloatToUnsignedChar(outputf,tmp);
			//convertFloatToUnsignedChar(inputf,in);
			watershed(tmp, tmp2);
			for(int x=0;x<xd;++x){
				for(int y=0;y<in.dim(1);++y){
					result(x,y,count)                    =blur(x,y);
					result(x+xd,y,count)          =tmp(x,y);
					result(x+(xd*2),y,count)      =tmp2(x,y);
					if(count>0)
						result(x+(xd*3),y,count)   =result(x+(xd*3),y,(count-1));
					if(tmp2(x,y)==unsigned char(0))
						result(x+(xd*3),y,count)  +=float(250/(s_final/stepsize));				
				}
			}
			count++;
		}

		if (!exportFile(result, "outcome.pip")) {
			 error("", "can't save file");
		}
		cout << "The result can be fount in 'outcome.pip', a 3d Image. \nThe z-axis is the scale space.\nFirst Image is the scaled one.\nSecond is the 'GRAD'\n 3rd is the watershed segmented Image. \n 4th Image is the density over all water-shed boarders over all segmentations 'so far'.\n BEWARE the Images for z==0 are still empty (sorry)...";

		cout << sw.stop() <<endl;
		system("pause");
        return 0;

			}